package com.victor.bingwallpaper.util;

import com.victor.bingwallpaper.lisenter.DownloadFinishListener;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUtils {

    public static void download(String address, String dir, String name, DownloadFinishListener listener) {
        (new Thread(()->{
            HttpURLConnection conn = null;
            FileOutputStream out = null;
            InputStream in = null;
            File saveFile = null;

            try {
                saveFile = new File(dir + "\\" + name);
                if (saveFile.exists()) {
                    saveFile.delete();
                }

                out = new FileOutputStream(saveFile);
                URL url = new URL(address);
                conn = (HttpURLConnection)url.openConnection();
                conn.setReadTimeout(5000);
                conn.setConnectTimeout(3000);
                conn.connect();
                in = conn.getInputStream();
                byte[] buffer = new byte[1024];

                int lenx;
                while((lenx = in.read(buffer)) != -1) {
                    out.write(buffer, 0, lenx);
                }

                listener.finish();
                out.close();
                in.close();
            } catch (Exception var11) {
                if (saveFile != null) {
                    saveFile.delete();
                }

                listener.error(var11);
            } finally {
                if (conn != null) {
                    conn.disconnect();
                }

            }
        })).start();
    }
    public static HttpURLConnection getHttpUrlConnection(String url) throws Exception {
        URL httpUrl = new URL(url);
        HttpURLConnection connection = (HttpURLConnection)httpUrl.openConnection();
        connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36");
        return connection;
    }

    public static String getHttpContent(String url) {
        HttpURLConnection connection = null;
        StringBuilder stringBuilder = new StringBuilder();

        try {
            connection = getHttpUrlConnection(url);
            InputStream inputStream = connection.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(inputStream);
            byte[] buffer = new byte[1024];
            boolean var6 = true;

            int len;
            while((len = bis.read(buffer)) != -1) {
                stringBuilder.append(new String(buffer, 0, len));
            }

            String var7 = stringBuilder.toString();
            return var7;
        } catch (Exception var11) {
        } finally {
            if (connection != null) {
                connection.disconnect();
            }

        }

        return null;
    }
}
